
// http://code.google.com/apis/ajaxlibs/documentation/index.html#jqueryUI
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");

travelplanner = {}; // declare namespace

// Name of the field which will contain picked item ids, comma separated
travelplanner.formFieldName = "plan";

/* 
 * Update the hidden form field value based on all selected items
 */
travelplanner.updateForm = function() {

	var field = $('input[name=' + travelplanner.formFieldName + ']');
	if(field.size() <= 0) {
		alert("Your page lacks a proper input form - please add <input> with name " + travelplanner.formFieldName);
	}
	
	// Create concatenated list of selected ids;
	var value = "";
	$('.selected-plan .item').each( function() {
		value += $(this).attr("id");
		value += ", ";
	});

	// Update DOM value of the hidden input
	field.get(0).value = value;
};


/**
 * Scope: this = drop target area
 */
travelplanner.drop = function(event, ui) {

	// console.log("We are:" + this);

	// Hide help text
	$('.selected-plan .help-text').remove();

	// Make item available in the basker
	var selectedItem = ui.draggable.clone();	

	$('.selected-plan').append(selectedItem);


	// Closure function which handles removing of the created basket item
	function remove() {
		selectedItem.remove();
	}

	// bind click even for the remove item
	$(selectedItem).find('.remove').click(remove);

	// Update the hidden field value
	travelplanner.updateForm();
};

/**
 * Initialize JQuery UI
 *
 * http://blog.endpoint.com/2009/12/jquery-ui-drag-drop-tips-ecommerce.html
 *
 */
travelplanner.bootstrap = function() {

	$('.item').draggable({
		opacity: 0.7,
		helper: 'clone',
		cursorAt : { top:0, left:0 }
	});

	$('.selected-plan').droppable({
		drop : travelplanner.drop,
		hoverClass : 'item-arrived'
	});

};

// http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/
google.setOnLoadCallback(travelplanner.bootstrap);
